<template>
  <div style="font-size: 20px; margin-left: 20%; margin-bottom: 20px">采购订单</div>
  <el-form :label-position="top" label-width="auto" style="max-width: 50%">
    <el-form-item label="会员名称">
      <el-select
        v-model="formData.memberId"
        placeholder="请选择会员"
        filterable
        default-first-option
        clearable
      >
        <el-option
          v-for="member in members"
          :key="member.id"
          :label="member.label"
          :value="member.id"
        />
      </el-select>
    </el-form-item>
    <div v-for="(item, index) in formDataList" :key="index">
      <el-form-item label="购买药品名称">
        <el-select
          v-model="item.medicineId"
          placeholder="请选择购买药品"
          filterable
          default-first-option
          clearable
        >
          <el-option
            v-for="medicine in medicines"
            :key="medicine.id"
            :label="medicine.label"
            :value="medicine.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="购买数量">
        <el-input v-model="item.quantity" placeholder="请输入购买数量" clearable />
      </el-form-item>
      <el-form-item label="购买单价">
        <el-input v-model="item.unitPrice" placeholder="自动填充单价" readonly clearable />
      </el-form-item>
      <el-form-item label="小计金额">
        <el-input v-model="item.subtotal" readonly clearable />
        <el-button
          v-if="index === formDataList.length - 1"
          @click="addFormItem"
          style="margin-top: 8px"
        >
          添加新项
        </el-button>
      </el-form-item>
    </div>
    <el-form-item label="会员折扣">
      <el-input v-model="formData.discount" placeholder="请输入会员折扣" clearable />
    </el-form-item>
    <el-form-item label="收银员">
      <el-select
        v-model="formData.cashierId"
        placeholder="请输入收银员姓名"
        filterable
        default-first-option
        clearable
      >
        <el-option
          v-for="cashier in cashiers"
          :key="cashier.id"
          :label="cashier.label"
          :value="cashier.id"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="应支付金额">
      <el-input :model-value="totalAmount" readonly />
    </el-form-item>
    <el-form-item label="实际支付金额">
      <el-input :model-value="finalAmount" readonly />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitButton" style="margin-left: 40%">出售</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import { reactive, computed, onMounted, toRaw, watch, watchEffect } from 'vue'
import myAxios from '../../axios/myAxios'
import { ElMessage } from 'element-plus'
import { useUserStore } from '../../stores/userStore'

interface MedicineSale {
  saleId: number
  memberId: number
  totalAmount: number
  discount: number
  finalAmount: number
  saleDate: string
  cashierId: number
  detailId: number
  medicineId: number
  quantity: number
  unitPrice: number
  subtotal: number
}

const userStore = useUserStore()
const formData = reactive({
  cashierId: userStore.userInfo.id,
  memberId: null,
  discount: 10,
})

const formDataList = reactive<MedicineSale[]>([createNewSaleItem()])

function createNewSaleItem(): MedicineSale {
  return {
    saleId: null,
    memberId: null,
    totalAmount: null,
    discount: 10,
    finalAmount: 0,
    saleDate: '',
    cashierId: null,
    detailId: null,
    medicineId: null,
    quantity: null,
    unitPrice: null,
    subtotal: null,
  }
}

// 添加新采购项并设置监听
const addFormItem = () => {
  const newItem = createNewSaleItem()
  formDataList.push(newItem)
  formDataList.forEach(setupMedicineWatcher)
}

// 自动填充单价逻辑
const setupMedicineWatcher = (item: MedicineSale) => {
  watch(
    () => item.medicineId,
    (newVal) => {
      console.log(newVal)
      if (newVal) {
        const medicine = medicines.find((m) => m.id === newVal)
        if (medicine) {
          item.unitPrice = medicine.price
        }
      }
    },
  )
}

// 计算逻辑
watchEffect(() => {
  formDataList.forEach((item) => {
    item.subtotal = (item.quantity || 0) * (item.unitPrice || 0)
  })
})

const totalAmount = computed(() =>
  formDataList.reduce((sum, item) => sum + (item.subtotal || 0), 0),
)

const finalAmount = computed(() => totalAmount.value * (formData.discount / 10))

// 数据初始化
const medicines = reactive<{ id: number; label: string; price: number; stock: number }[]>([])
const members = reactive<{ id: number; label: string }[]>([])
const cashiers = reactive<{ id: number; label: string }[]>([])
const idToStock = reactive<Record<number, number>>({})
const idToMember = reactive<Record<number, number>>({})

onMounted(() => {
  // 初始化药品数据
  myAxios.get('medicine/list').then((res) => {
    const filteredMedicines = res.data.data.records.filter((item) => item.status === '在售')
    filteredMedicines.forEach((item) => {
      medicines.push({
        id: item.id,
        label: item.name,
        price: item.price, // 确保接口返回price字段
        stock: item.stock,
      })
      idToStock[item.id] = item.stock
    })
  })

  // 初始化会员数据
  myAxios.get('member/list').then((res) => {
    res.data.data.records.forEach((item) => {
      members.push({ id: item.id, label: item.name })
      idToMember[item.id] = item.points
    })
  })

  // 初始化收银员数据
  myAxios.get('user/list').then((res) => {
    res.data.data.records.forEach((item) => {
      cashiers.push({ id: item.id, label: item.username })
    })
  })

  // 初始化监听
  formDataList.forEach(setupMedicineWatcher)
})

// 提交逻辑
const submitButton = () => {
  let flag = true
  formDataList.forEach((item) => {
    if (item.quantity > idToStock[item.medicineId]) {
      ElMessage.error(
        medicines.find((m) => m.id === item.medicineId).label +
          '库存只有' +
          idToStock[item.medicineId] +
          '件',
      )
      flag = false
      return
    }
  })
  if (flag) {
    myAxios
      .post('sales/create', {
        memberId: formData.memberId,
        cashierId: formData.cashierId,
        discount: formData.discount,
        finalAmount: finalAmount.value,
        totalAmount: totalAmount.value,
      })
      .then((res) => {
        if (res.data.code === 200) {
          myAxios
            .post(
              'sales/detail/batch-create',
              toRaw(formDataList).map((item) => ({
                medicineId: item.medicineId,
                quantity: item.quantity,
                unitPrice: item.unitPrice,
                subtotal: item.subtotal,
                saleId: res.data.data.saleId,
              })),
            )
            .then((res) => {
              if (res.data.code === 200) {
                ElMessage.success('出售成功')
                // 更新库存
                toRaw(formDataList).forEach((item) => {
                  myAxios.put('medicine/update', {
                    id: item.medicineId,
                    stock: idToStock[item.medicineId] - item.quantity,
                  })
                })
                // 更新会员积分
                if (formData.memberId) {
                  myAxios.put('member/update', {
                    id: formData.memberId,
                    points: idToMember[formData.memberId] + finalAmount.value,
                  })
                }
              }
            })
        }
      })
  }
}
</script>
